const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");
let mimeData = require("./mime.json");  // 自动把json数据转成对象
let resdata = require("./data.json");
// console.log(typeof mimeData);
const server = http.createServer((req, res) => {
    console.log(req.url);
    var urlRes = url.parse(req.url,true);
    // console.log(urlRes);
    let pathname = urlRes.pathname;
    // console.log(`姓名是${urlRes.query.name}年龄是${urlRes.query.age}`);
    // /index  和  /index?name=zhangsan
    res.setHeader("Content-Type", "text/html;charest=utf-8");
    if (pathname == "/index" || pathname=="/") {
        let data = fs.readFileSync("./views/index.html");
        res.write(data);
        res.end();
    }else if(pathname == "/product"){
        let data = fs.readFileSync("./views/product.html");
        res.write(data);
        res.end();
    }else if(pathname == "/getdata"){
        console.log(urlRes.query);
        res.write(JSON.stringify(resdata));
        res.end();
    }else if(pathname == "/getpostdata"){
        // nodejs里获取post参数 ，通过流来获取
        let str = "";
        req.on("data",chunk=>{
            str += chunk;
        })

        req.on("end",()=>{
            console.log(str);
        })

        res.write(JSON.stringify({name:123,height:"178cm"}));
        res.end();
    } else{
        // 第三方资源
        // MIME 配置文件
        console.log("??",req.url)
        if(req.url!="/favicon.ico"){  // 图标不做加载
            // 获取资源的后缀名
            let extname =  path.extname(req.url);
    //    console.log(extname);
            let contenttype = mimeData[extname];
            // 根据资源后缀设置返还头部
            res.setHeader("Content-Type",contenttype);
            let data = fs.readFileSync("./static/"+req.url)
            res.write(data);
            res.end();
        }
    }
})
server.listen(8989);